var async = require('async');
var helpers = require('../../../helpers/aws');

module.exports = {
    title: 'Amazon ECR Scan on Push',
    category: 'ECR',
    domain: 'Containers',
    severity: 'Medium',
    description: 'Ensures Amazon ECR container images are automatically scanned for security vulnerabilities after being pushed to a repository.',
    more_info: 'Scan on Push for Amazon ECR is an automated vulnerability assessment feature that helps improve the security of ECR container images by scanning them for OS vulnerabilities.',
    link: 'https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html#scanning-on-push',
    recommended_action: 'Enable "Scan on Push" for your Amazon ECR repositories.',
    apis: ['ECR:describeRepositories'],
    realtime_triggers: ['ecr:CreateRepository', 'ecr:PutImageScanningConfiguration', 'ecr:DeleteRepository'],

    run: function(cache, settings, callback) {
        var results = [];
        var source = {};
        var regions = helpers.regions(settings);

        async.each(regions.ecr, function(region, rcb) {
            var describeRepositories = helpers.addSource(cache, source,
                ['ecr', 'describeRepositories', region]);

            if (!describeRepositories) return rcb();

            if (describeRepositories.err || !describeRepositories.data) {
                helpers.addResult(
                    results, 3,
                    'Unable to query for ECR repositories: ' + helpers.addError(describeRepositories), region);
                return rcb();
            }

            if (!describeRepositories.data.length) {
                helpers.addResult(results, 0, 'No ECR repositories present', region);
                return rcb();
            }

            for (var repository of describeRepositories.data) {
                var resource = repository.repositoryArn;
             
                if (repository.imageScanningConfiguration && repository.imageScanningConfiguration.scanOnPush) {
                    helpers.addResult( results,  0,
                        'Scan on Push is enabled for ECR repository', region, resource);
                } else {
                    helpers.addResult( results, 2,
                        'Scan on Push is not enabled for ECR repository', region, resource);
                }
            }

            rcb();
        }, function() {
            callback(null, results, source);
        });
    }
};
